<!-- 优惠券列表 -->
<template>
  <div class="container">
    <!-- 搜索框和添加按钮 -->
    <div class="search-container">
      <el-input v-model="search" size="small" placeholder="请输入商品名称搜索" style="width: 200px;" clearable>
        <template #prefix>
          <el-icon>
            <Search />
          </el-icon>
        </template>
      </el-input>
      <el-button type="primary" @click="showAddCouponDialog" style="margin-left: 16px;">
        添加新优惠券
      </el-button>
    </div>

    <!-- 表格部分 -->
    <el-scrollbar>
      <el-table :data="filterTableData1" style="width: 100%" height="700">
        <!-- 优惠券ID -->
        <el-table-column prop="couponId" label="优惠券ID" show-overflow-tooltip />

        <!-- 优惠券金额 -->
        <el-table-column prop="amount" label="优惠券金额" show-overflow-tooltip>
          <template #default="{ row }">
            <el-input
              v-if="row.isEdit"
              v-model="row.amount"
              type="number"

              size="small"
              placeholder="请输入优惠金额"
              @input="validateAmount(row)"
              style="width: 120px"
            >
              <template #prefix>
                <span>￥</span>
              </template>
            </el-input>
            <span v-else>￥{{ row.amount }}</span>
          </template>
        </el-table-column>

        <!-- 适用商品ID -->
        <el-table-column prop="productId" label="适用商品ID" show-overflow-tooltip>
          <template #default="{ row }">
            <el-select
              v-if="row.isEdit"
              v-model="row.productId"
              filterable
              placeholder="请选择商品"
              size="small"
              @change="handleProductSelect($event, row)"
            >
              <el-option
                v-for="item in productOptions"
                :key="item.productId"
                :label="`${item.productId} - ${item.name}`"
                :value="item.productId"
              >
                <div class="select-item">
                  <img 
                    :src="'http://localhost:8081' + item.image" 
                    style="width: 30px; height: 30px; margin-right: 10px;"
                  >
                  <span>ID: {{ item.productId }} - {{ item.name }}</span>
                </div>
              </el-option>
            </el-select>
            <span v-else>{{ row.productId }}</span>
          </template>
        </el-table-column>

        <!-- 商品名称 -->
        <el-table-column prop="name" label="商品名称" show-overflow-tooltip />

        <!-- 商品图片 -->
        <el-table-column prop="image" label="图片">
          <template #default="{ row }">
            <img v-if="row.image" :src="'http://localhost:8081' + row.image" alt="商品图片"
              style="width: 50px; height: 50px" />
            <span v-else>暂无图片</span>
          </template>
        </el-table-column>

        <!-- 优惠券数量 -->
        <el-table-column prop="quantity" label="优惠券总数量" show-overflow-tooltip />

        <!-- 商品单价 -->
        <el-table-column prop="price" label="商品单价" show-overflow-tooltip />

        <!-- 是否停止发放 -->
        <el-table-column prop="isDelete" label="是否停止发放" show-overflow-tooltip>
          <template #default="{ row }">
            {{ row.isDelete === '0' ? '继续' : '停止' }}
          </template>
        </el-table-column>

        <!-- 操作列 -->
        <el-table-column label="操作" width="180">
          <template #default="{ row }">
            <el-button v-if="!row.isEdit" type="primary" @click="editRow(row)">修改</el-button>
            <el-button v-else type="success" @click="saveRow(row)">保存</el-button>
            <el-button v-if="row.isEdit" @click="cancelEdit(row)">取消</el-button>
            <el-button v-if="!row.isEdit" type="danger" @click="deleteRow(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 添加分页组件 -->
      <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[6, 12, 24, 48]"
        :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange"
        layout="total, sizes, prev, pager, next" class="pagination" />
    </el-scrollbar>
    <!-- 添加优惠券对话框组件 -->
    <AddCoupon ref="addCouponRef" @refresh-list="refreshList"></AddCoupon>
  </div>
</template>

<script setup>
import { ElMessage, ElMessageBox } from 'element-plus'
import { onMounted, ref, computed } from "vue";
import axios from "axios";
import { Search } from '@element-plus/icons-vue'
import AddCoupon from './AddCoupon.vue'
const coupons = ref([]);
const originalCoupons = ref([]);

const editRow = (row) => {
  row.isEdit = true;
};
const deleteRow = async (row) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这个优惠券吗？此操作不可恢复',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    const response = await axios.post('/deleteCoupon',
      row.couponId,
      {
        headers: {
          'Content-Type': 'application/json',
          Authorization: sessionStorage.getItem('Authorization')
        }
      }
    )
    if (response.data.status === 200) {
      ElMessage.success(response.data.message);
      coupons.value = coupons.value.filter(coupon => coupon.couponId !== row.couponId);
    } else {
      ElMessage.error(response.data.message);
    }
  } catch (error) {
    if (error === 'cancel') {
      ElMessage.info('已取消删除')
    } else {
      ElMessage.error('删除失败');
    }
  }
};

const cancelEdit = (row) => {
  const index = coupons.value.indexOf(row);
  if (index !== -1) {
    if (row.isNew) {
      coupons.value.splice(index, 1);
    } else {
      const originalRow = originalCoupons.value[index];
      coupons.value[index] = { ...originalRow, isEdit: false };
    }
  }
};
const saveRow = async (row) => {
  try {
    // 1. 验证输入
    if (!row.productId || !row.amount || !row.quantity) {
      ElMessage.warning('请填写完整信息');
      return;
    }

    // 2. 验证金额
    const amount = parseFloat(row.amount);
    if (isNaN(amount) || amount <= 0) {
      ElMessage.warning('请输入有效的优惠券金额');
      return;
    }

    // 3. 验证数量
    if (row.quantity <= 0) {
      ElMessage.warning('优惠券数量必须大于0');
      return;
    }

    // 其他验证逻辑保持不变...
    const existingCoupon = coupons.value.find(coupon => 
      coupon.couponId !== row.couponId && 
      coupon.productId === row.productId && 
      parseFloat(coupon.amount) === amount &&
      coupon.isDelete === '0'
    );

    if (existingCoupon) {
      ElMessage.warning('已存在相同商品和金额的优惠券');
      return;
    }

    // 4. 发送更新请求
    const response = await axios.post(
      "/updateCoupons",
      {
        couponId: row.couponId,
        amount: amount,
        quantity: row.quantity,
        isDelete: row.isDelete,
        productId: row.productId,
      },
      {
        headers: {
          Authorization: sessionStorage.getItem("Authorization"),
        },
      }
    );

    // 可以在这里更新用户的状态，例如关闭编辑模式
    row.isEdit = false;
    if (response.data.status === 200 || response.data.status === 500) {
      ElMessage.success('保存成功');
      row.isEdit = false;
      row.avatarFile = null; // 清除临时文件

    }
    else {
      console.log(response.data);
    }
  } catch (error) {
    console.error('保存失败:', error);
    ElMessage.error(error.response?.data?.message || '保存失败');
  }
};
onMounted(() => {
  fetchProducts();
  refreshList();
});
const search = ref(""); // 响应式搜索变量
// 计算属性，根据搜索值过滤列表
const filterTableData1 = computed(() =>
  coupons.value.filter(
    (coupon) =>
      !search.value ||
      coupon.name.toLowerCase().includes(search.value.toLowerCase())
  )
);

// 添加对话框相关方法
const addCouponRef = ref(null)
const showAddCouponDialog = () => {
  if (addCouponRef.value) {
    addCouponRef.value.dialogVisible = true
  } else {
    ElMessage.error('组件加载失败')
  }
}

// 添加分页相关的响应式变量
const currentPage = ref(1)
const pageSize = ref(6)
const total = ref(0)

// 修改获取优惠券列表的方法
const refreshList = async () => {
  try {
    // 获取优惠券列表
    const couponsResponse = await axios.get("/getCoupon", {
      params: {
        current: currentPage.value,
        size: pageSize.value
      },
      headers: {
        Authorization: sessionStorage.getItem("Authorization"),
      },
    });

    // 获取商品列表 - 这里不需要分页，获取所有商品
    const productsResponse = await axios.get("/getGoods", {
      params: {
        current: 1,
        size: 999999  // 设置一个足够大的数来获取所有商品
      },
      headers: {
        Authorization: sessionStorage.getItem("Authorization"),
      },
    });

    // 将商品信息合并到优惠券数据中 - 修改这里使用 records
    const mergedCoupons = couponsResponse.data.data.records.map(coupon => {
      const matchedProduct = productsResponse.data.data.records.find(
        product => product.productId === coupon.productId
      );

      return {
        ...coupon,
        isEdit: false,
        name: matchedProduct?.name || '商品已删除',
        image: matchedProduct?.image || '',
        price: matchedProduct?.price || 0
      };
    });

    // 更新数据
    coupons.value = mergedCoupons;
    total.value = couponsResponse.data.data.total;
    originalCoupons.value = JSON.parse(JSON.stringify(mergedCoupons));

  } catch (error) {
    console.error(error);
    ElMessage.error(error.message || '获取数据失败');
  }
};

// 处理页码改变
const handleCurrentChange = (val) => {
  currentPage.value = val;
  refreshList();
}

// 处理每页显示数量改变
const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1; // 重置为第一页
  refreshList();
}

// 添加商品选项列表
const productOptions = ref([]);

// 修改获取商品列表的方法
const fetchProducts = async () => {
  try {
    const response = await axios.get("/getGoods", {
      params: {
        current: 1,
        size: 999999
      },
      headers: {
        Authorization: sessionStorage.getItem("Authorization"),
      },
    });
    productOptions.value = response.data.data.records;
  } catch (error) {
    console.error(error);
    ElMessage.error('获取商品列表失败');
  }
};

// 修改商品选择处理函数
const handleProductSelect = (productId, row) => {
  const selectedProduct = productOptions.value.find(item => item.productId === productId);
  if (selectedProduct) {
    row.name = selectedProduct.name;
    row.image = selectedProduct.image;
    row.price = selectedProduct.price;
  }
};

// 添加金额验证函数
const validateAmount = (row) => {
  // 确保输入为数字
  if (isNaN(row.amount)) {
    row.amount = '';
    return;
  }

  // 转换为数字处理
  let amount = parseFloat(row.amount);

  // 限制小数点后两位
  if (amount.toString().includes('.')) {
    const parts = amount.toString().split('.');
    if (parts[1].length > 2) {
      amount = parseFloat(amount.toFixed(2));
      row.amount = amount;
    }
  }

  // 确保金额大于0
  if (amount <= 0) {
    row.amount = '';
    ElMessage.warning('优惠券金额必须大于0');
    return;
  }

  // 可以设置最大金额限制（根据需求调整）
  if (amount > 10000) {
    row.amount = 10000;
    ElMessage.warning('优惠券金额不能超过10000元');
    return;
  }
};

</script>
<style scoped>
.container {
  display: flex;
  flex-direction: column;
  width: 100%;
}

.search-container {
  width: 100%;
  padding: 20px;
  background-color: #fff;
  border-bottom: 1px solid #ebeef5;
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  /* 使搜索框和按钮垂直居中对齐 */
}

/* 样式根据需要进行调整 */
.ellipsis {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.scrollbar-demo-item {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 50px;
  margin: 10px;
  text-align: center;
  border-radius: 4px;
  background: var(--el-color-primary-light-9);
  color: var(--el-color-primary);
}

/* 添加分页组件的样式 */
.pagination {
  display: flex;
  justify-content: center;
  /* 水平居中 */
  align-items: center;
  /* 垂直居中 */
}

.select-item {
  display: flex;
  align-items: center;
  padding: 5px;
}

.select-item img {
  object-fit: cover;
  border-radius: 4px;
}

/* 添加金额输入框样式 */
:deep(.el-input-number) {
  width: 100%;
}

:deep(.el-input__prefix) {
  color: #909399;
  font-size: 14px;
}
</style>